<template>
  <div class="add-up-box" v-if="domShow" v-loading="loading">
    <a-upload :action="action" :auto-upload="false" :beforeUpload="beforeUpload" >
      <a-button v-if="mode" type="primary" @click="getUploadUrl">上传附件</a-button>
    </a-upload>
    <div class="add-up-list">
      <div
        v-for="(item,index) in StuFillAnswer"
        :key="index"
        class="add-up-lis"
      >
        {{item.DocTitle}}
        <span @click="getShow(item,1)" style="margin-right: 10px;">下载</span>
        <span @click="getShow(item,2)" style="margin-right: 10px;" v-if="item.DocType.toLowerCase() != 'rar' && item.DocType.toLowerCase() != 'zip' &&  item.DocType.toLowerCase() != 'mov'">查看</span>
        <a-icon
          v-if="mode"
          @click.stop="delFileAnswer(item.Id,index)"
          type="close"
          class="add-lis-close"
          style="color: #f00;vertical-align: middle;font-size: 18px;"
        />
      </div>
    </div>
    <div class="mc-exam" v-show="Show" @click.stop="getPreviewShow">
      <div
        style="position: fixed;right: 50px;top: 28px;color: #fff;z-index: 1000;cursor: pointer;"
        @click.stop="getPreviewShow"
      >
        <i class="iconfont icon-remove" style="font-size: 24px;"></i>
      </div>
      <preview :data="upData" :Show='Show' ref="child" :imgDeg="imgDeg"></preview>
    </div>
  </div>
</template>

<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
import preview from '@/components/filePreview/index.vue';
export default {
  components: {
    preview
  },
  data() {
    return {
      loading: false,
      // imageUrl: '',
      action: '',
      file_system_url: '',
      cahceFileList: [],
      fileList: [],
      //  点击预览图片
      previewImage: '',
      StuFillAnswer: [],
      downloadUrl: '',
      upData: {},
      lis: {
        ResId: '',
        DocTitle: '',
        Url: '',
        DocType: ''
      },
      upShow: 0,
      domShow: true,
      Show: false,
      upType: ['css', 'js', 'exe','dll','jmx','mmap','pem','xml'],
      uploadType: '',
      upTypeShow: false,
      imgDeg: 0,
      ossUrl: ''
    };
  },
  destroyed() {
      clearInterval(this.ossUrl);
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    examId: {
      type: String,
      default: ''
    },
    workExamStuId: {
      type: String,
      default: ''
    },
    index: {
      type: Number,
      default: 0
    },
    mode: { //默认能上传和删除文件
      type: Boolean,
      default: true
    }
  },
  mounted() {
      this.StuFillAnswer = this.data.fileList || [];
      var dom = document.getElementsByClassName('ant-upload-list');
      dom[0].style = 'max-height: 90px;overflow: auto;';
  },
  methods: {
      getUploadUrl() {
          this.$http.post('/api/common/LocalStorage/getUploadUrl').then((rst) => {
        if (rst.code == 1) {
          this.file_system_url = rst.file_system_url_oss;
          this.oss = rst.signature;
        } else {
          this.$message.error('获取上传接口失败！');
        }
      });
    },
    getPreviewShow() {
      this.Show = false;
      this.imgDeg = 0;
      this.upData = {};
      this.$refs.child.setVideo();
    },
    getShow(item,type) {
      if (type == 1) {
        this.$http
          .post('/common/ueditor/previewUrl', {
            url: item.Url,
            title: item.DocTitle
          })
          .then((res) => {
            window.open(res.downloadUrl);
          });
      } else if(type == 2){
        this.upData = item;
        this.Show = true;
      }
    },
    beforeUpload(file) {
      this.loading = true;
      let ext = file.name.split('.')[1];
      let flag = this.upType.includes(ext.toLowerCase());
      let type = file.type.split('/')[1];
      // oss 上传对象
      let data = Object.assign(file, {
        key: `${this.oss.dir}/${this.oss.random}/${file.name}`,
        policy: this.oss.policy,
        callback: this.oss.callback,
        signature: this.oss.signature,
        success_action_status: 200,
        OSSAccessKeyId: this.oss.accessid,
        // 'x:userid': oss.userid,
        'x:space': this.oss.spaceName,
        'x:identity': this.oss.identity,
        'x:name': file.name,
        file: file
      });
      let formData = new FormData();
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
      if (flag) {
          this.loading = false;
          this.$message.warning('该类型不允许上传');
      } else {
        this.$http.post(this.file_system_url, formData, {
          withCredentials: false,
          headers: {
            'Content-Type': 'multipart/form-data; boundary={boundary}'
          }
        }).then((res) => {
          this.onlineExamFile(file,res);
        });
      }
      return false
    },
    onlineExamFile(e,data) {
      var useTime = localStorage.removeItem('useTime' + this.workExamStuId);
      var that = this;
      this.$http
        .post('/api/study/workexam/onlineExamFile', {
          examId: this.examId, //考试Id
          workExamStuId: this.workExamStuId, //学生作答Id
          questionId: this.data.QuestionId, //题目Id
          docTitle: e.name, //文件标题
          docType: e.name.substring(e.name.lastIndexOf('.')).split('.')[1], //文件类型
          docSize: data.size, //文件大小
          md5: data.md5,
          url: data.url,
          sourceType: 1, //数据来源，1、web,2、 android,3、 ios
          useTime: useTime //作答时间
        })
        .then((res) => {
          if (res.code > 0) {
            this.loading = false;
            this.lis.ResId = res.id;
            this.lis.DocTitle = e.name;
            this.lis.Url = data.url;
            this.lis.DocType = e.name.substring(e.name.lastIndexOf('.')).split('.')[1];
            this.fileList.push(this.lis);
            this.StuFillAnswer.push(this.lis);
            this.data.fileList = this.StuFillAnswer;
            this.lis = {
              ResId: '',
              DocTitle: '',
              Url: '',
              DocType: ''
            };
          }
        });
    },
    delFileAnswer(id, index) {
      this.$http
        .post('/api/study/workexam/delFileAnswer', {
          id: id
        })
        .then((res) => {
          if (res.code > 0) {
            this.StuFillAnswer.splice(index, 1);
            this.data.fileList = this.StuFillAnswer;
          }
        });
    }
  }
};
</script>
